import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import { createPaginationResponse, parsePaginationParams } from '@/lib/pagination';
import { User } from '@/types/user';
import { PaginationResponse } from '@/types/api-common';
import { Prisma } from '@prisma/client';

async function handlePost(request: NextRequest): Promise<PaginationResponse<User>> {
  const authResult = await authenticateRequest(request);
  if (!authResult.success || !authResult.user || authResult.user.role !== 1) {
    throw new Error('权限不足');
  }

  const body = await request.json();
  const { page, pageSize, skip } = parsePaginationParams(body);
  const { username, nickname, email, role, status } = body;

  const where: Prisma.UserWhereInput = {};

  if (username) {
    where.username = { contains: username };
  }

  if (nickname) {
    where.nickname = { contains: nickname };
  }

  if (email) {
    where.email = { contains: email };
  }

  if (role) {
    where.role = role;
  }

  if (status) {
    where.status = status;
  }

  const [users, total] = await Promise.all([
    prisma.user.findMany({
      where,
      skip,
      take: pageSize,
      orderBy: {
        createdAt: 'desc',
      },
      select: {
        id: true,
        username: true,
        email: true,
        nickname: true,
        avatar: true,
        role: true,
        status: true,
        createdAt: true,
        updatedAt: true,
      },
    }),
    prisma.user.count({ where }),
  ]);

  const formattedUsers = users.map((user) => ({
    ...user,
    email: user.email || '',
    nickname: user.nickname || '',
    avatar: user.avatar || '',
  }));

  return createPaginationResponse(formattedUsers, total, page, pageSize);
}

export const POST = withMiddleware(handlePost);